<?php
/**
 * 使用gitee webhook 自动部署网站
 */

//网站根目录绝对路径(以/结尾,如/www/wwwroot/website/)
$webPath = dirname(__DIR__) . DIRECTORY_SEPARATOR;

//WebHook密钥信息
$webHookSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';

/**
 * 写日志函数
 * @param $str '日志字符串'
 */
function writeLog($str) {
    file_put_contents('webhook.log', $str, FILE_APPEND | LOCK_EX);
}

//以流的方式读取传输过来的json
$body = file_get_contents("php://input");
if (empty($body)) {
    die('无输入');
}

//json转换为array
$body = json_decode($body, true);

//签名校验 (文档详见: https://gitee.com/help/articles/4290)
$secretJoin = $body['timestamp'] . "\n" . $webHookSecret;
$mySign = base64_encode(hash_hmac('sha256', $secretJoin, $webHookSecret, true));
if ($mySign !== $body['sign']) {
    die('签名错误');
}

//获取推送分支
$branch = str_replace('refs/heads/', '', $body['ref']);

//执行更新
$cmd[] = 'cd ' . $webPath;
$cmd[] = 'git config core.filemode false 2>&1';
$cmd[] = 'git pull origin master 2>&1';
$cmd[] = 'chown -R www:www ' . $webPath . '* 2>&1';
$cmd[] = 'chmod -R 755 ' . $webPath . '* 2>&1';
$cmd[] = 'php think api -froce 2>&1';
$cmdStr = implode(' && ', $cmd);

$output = shell_exec($cmdStr);

//输出执行结果
die('执行结果:' . json_encode($output));